import Alertift
import ProgressHUD
import UIKit

struct Customer: Codable {
  let nickName: String
  let headImageUrl: String?
  let wxMemberId: String?
  let unionId: String?

  //    0-已关注 1-未关注
  let followVisitorStatus: Int
  let followType: Int  // 关注类型  0-app关注   1-点击关注 -1 -不存在

}

class CustomerViewController: UIViewController {

  private let taskId: Int

  init(taskId: Int) {
    self.taskId = taskId
    super.init(nibName: nil, bundle: nil)
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  // MARK: - Properties
  private var starredCustomers: [Customer] = [] {
    didSet {
      starredTitleLabel.text = "已关注重点客户(\(starredCustomers.count))"
      updateStarredCustomersView()
    }
  }

  private var potentialCustomers: [Customer] = [] {
    didSet {
      potentialTitleLabel.text = "高意向客户列表(\(potentialCustomers.count))"
      potentialCollectionView.reloadData()
      updatePotentialCustomersView()
    }
  }

  // 搜索的防抖
  private var debounceWorkItem: DispatchWorkItem?

  // MARK: - UI Components
  private let starredCustomersView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .white
    view.layer.cornerRadius = 10
    return view
  }()

  private let starredTitleLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "已关注重点客户(0)"
    label.font = .systemFont(ofSize: 16, weight: .medium)
    return label
  }()

  private let emptyStarredLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "未添加重点客户"
    label.textAlignment = .center
    label.textColor = .gray
    label.font = .systemFont(ofSize: 14)
    return label
  }()

  private let emptyStarredDescLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "请在下方客户列表中选择添加重点客户"
    label.textAlignment = .center
    label.textColor = .gray
    label.font = .systemFont(ofSize: 12)
    return label
  }()

  private let potentialCustomersView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .white
    view.layer.cornerRadius = 10
    return view
  }()

  private let potentialTitleLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "高意向客户列表(0)"
    label.font = .systemFont(ofSize: 16, weight: .medium)
    return label
  }()

  private lazy var searchBar: UISearchBar = {
    let searchBar = UISearchBar()
    searchBar.translatesAutoresizingMaskIntoConstraints = false
    searchBar.placeholder = "请输入用户昵称"
    searchBar.searchBarStyle = .minimal
    searchBar.delegate = self
    if let textField = searchBar.value(forKey: "searchField") as? UITextField {
      textField.returnKeyType = .done
    }
    return searchBar
  }()

  private let emptyPotentialLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "暂无内容"
    label.textAlignment = .center
    label.textColor = .gray
    label.font = .systemFont(ofSize: 14)
    return label
  }()

  /**
   * 已关注重点客户 CollectionView
   */
  private lazy var followedCollectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumInteritemSpacing = 10
    layout.minimumLineSpacing = 10

    let collectionView = UICollectionView(
      frame: .zero,
      collectionViewLayout: layout
    )
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView
      .register(
        CustomerCell.self,
        forCellWithReuseIdentifier: "FollowedCell"
      )
    collectionView.backgroundColor = .white
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.showsHorizontalScrollIndicator = false
    return collectionView
  }()

  /**
   * 高意向客户列表 CollectionView
   */
  private lazy var potentialCollectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
    layout.minimumInteritemSpacing = 10
    layout.minimumLineSpacing = 20

    let collectionView = UICollectionView(
      frame: .zero,
      collectionViewLayout: layout
    )
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView
      .register(
        CustomerCell.self,
        forCellWithReuseIdentifier: "PotentialCell"
      )
    collectionView.backgroundColor = .white
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.showsVerticalScrollIndicator = false
    collectionView.keyboardDismissMode = .onDrag
    return collectionView
  }()

  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
    // 点击空白退出键盘
    enableSmartTapToDismissKeyboard()
  }
  let mobPageName = "app-客户"
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    MobClick.beginLogPageView(mobPageName)
    fetchCustomers()
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    MobClick.endLogPageView(mobPageName)
  }

  // MARK: - UI Setup
  private func setupUI() {
    view.backgroundColor = UIColor(
      red: 245 / 255,
      green: 245 / 255,
      blue: 245 / 255,
      alpha: 1
    )
    //        title = "我的客户"
    navigationItem.title = "我的客户"

    view.addSubview(starredCustomersView)
    starredCustomersView.addSubview(starredTitleLabel)
    starredCustomersView.addSubview(emptyStarredLabel)
    starredCustomersView.addSubview(emptyStarredDescLabel)
    starredCustomersView.addSubview(followedCollectionView)

    view.addSubview(potentialCustomersView)
    potentialCustomersView.addSubview(potentialTitleLabel)
    potentialCustomersView.addSubview(searchBar)
    potentialCustomersView.addSubview(emptyPotentialLabel)
    potentialCustomersView.addSubview(potentialCollectionView)

    NSLayoutConstraint.activate(
      [
        // 已关注客户视图约束
        starredCustomersView.topAnchor
          .constraint(
            equalTo: view.safeAreaLayoutGuide.topAnchor,
            constant: 10
          ),
        starredCustomersView.leadingAnchor
          .constraint(equalTo: view.leadingAnchor, constant: 15),
        starredCustomersView.trailingAnchor
          .constraint(equalTo: view.trailingAnchor, constant: -15),
        starredCustomersView.heightAnchor.constraint(equalToConstant: 200),

        starredTitleLabel.topAnchor
          .constraint(
            equalTo: starredCustomersView.topAnchor,
            constant: 15
          ),
        starredTitleLabel.leadingAnchor
          .constraint(
            equalTo: starredCustomersView.leadingAnchor,
            constant: 15
          ),

        emptyStarredLabel.centerXAnchor
          .constraint(equalTo: starredCustomersView.centerXAnchor),
        emptyStarredLabel.centerYAnchor
          .constraint(
            equalTo: starredCustomersView.centerYAnchor,
            constant: -10
          ),

        emptyStarredDescLabel.centerXAnchor
          .constraint(equalTo: starredCustomersView.centerXAnchor),
        emptyStarredDescLabel.topAnchor
          .constraint(
            equalTo: emptyStarredLabel.bottomAnchor,
            constant: 8
          ),

        followedCollectionView.topAnchor
          .constraint(
            equalTo: starredTitleLabel.bottomAnchor,
            constant: 10
          ),
        followedCollectionView.leadingAnchor
          .constraint(
            equalTo: starredCustomersView.leadingAnchor,
            constant: 8
          ),
        followedCollectionView.trailingAnchor
          .constraint(
            equalTo: starredCustomersView.trailingAnchor,
            constant: -8
          ),
        followedCollectionView.bottomAnchor
          .constraint(equalTo: starredCustomersView.bottomAnchor),

        // 潜在客户视图约束
        potentialCustomersView.topAnchor
          .constraint(
            equalTo: starredCustomersView.bottomAnchor,
            constant: 20
          ),
        potentialCustomersView.leadingAnchor
          .constraint(equalTo: view.leadingAnchor, constant: 15),
        potentialCustomersView.trailingAnchor
          .constraint(equalTo: view.trailingAnchor, constant: -15),
        potentialCustomersView.bottomAnchor
          .constraint(
            equalTo: view.safeAreaLayoutGuide.bottomAnchor,
            constant: -20
          ),

        potentialTitleLabel.topAnchor
          .constraint(
            equalTo: potentialCustomersView.topAnchor,
            constant: 15
          ),
        potentialTitleLabel.leadingAnchor
          .constraint(
            equalTo: potentialCustomersView.leadingAnchor,
            constant: 15
          ),

        searchBar.topAnchor
          .constraint(
            equalTo: potentialTitleLabel.bottomAnchor,
            constant: 5
          ),
        searchBar.leadingAnchor
          .constraint(
            equalTo: potentialCustomersView.leadingAnchor,
            constant: 5
          ),
        searchBar.trailingAnchor
          .constraint(
            equalTo: potentialCustomersView.trailingAnchor,
            constant: -5
          ),

        emptyPotentialLabel.centerXAnchor
          .constraint(equalTo: potentialCustomersView.centerXAnchor),
        emptyPotentialLabel.centerYAnchor
          .constraint(equalTo: potentialCustomersView.centerYAnchor),

        potentialCollectionView.topAnchor
          .constraint(equalTo: searchBar.bottomAnchor, constant: 10),
        potentialCollectionView.leadingAnchor
          .constraint(
            equalTo: potentialCustomersView.leadingAnchor,
            constant: 8
          ),
        potentialCollectionView.trailingAnchor
          .constraint(
            equalTo: potentialCustomersView.trailingAnchor,
            constant: -8
          ),
        potentialCollectionView.bottomAnchor
          .constraint(equalTo: potentialCustomersView.bottomAnchor),
      ]
    )
  }

  // MARK: - Data Loading
  private func fetchCustomers() {
    fetchFollowedData()
    fetchPotentialData()
  }

  //        已关注客户
  private func fetchFollowedData() {
    HttpClient.shared
      .postWithAutoHUD(endpoint: "/followedVisitors", body: ["taskId": taskId]) {
        [weak self]
        (
          customers: [Customer]?
        ) in
        guard let self = self else { return }
        if let customers = customers {
          self.starredCustomers = customers
          DispatchQueue.main.async {
            self.updateStarredCustomersView()
          }
        }
      }
  }

  // 高意向客户
  private func fetchPotentialData() {
    HttpClient.shared
      .postWithAutoHUD(
        endpoint: "/visitors", body: ["taskId": taskId, "nickNameOrPhone": searchBar.text ?? ""]
      ) {
        [weak self]
        (
          customers: [Customer]?
        ) in
        guard let self = self else { return }
        if let customers = customers {
          self.potentialCustomers = customers
          DispatchQueue.main.async {
            self.updatePotentialCustomersView()
          }
        }
      }
  }

  private func showLoadingView() -> UIView {
    let loadingView = UIView(frame: view.bounds)
    loadingView.backgroundColor = .white

    let activityIndicator = UIActivityIndicatorView(style: .medium)
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    loadingView.addSubview(activityIndicator)

    NSLayoutConstraint.activate([
      activityIndicator.centerXAnchor
        .constraint(equalTo: loadingView.centerXAnchor),
      activityIndicator.centerYAnchor
        .constraint(equalTo: loadingView.centerYAnchor),
    ])

    view.addSubview(loadingView)
    activityIndicator.startAnimating()

    return loadingView
  }

  private func updateStarredCustomersView() {
    emptyStarredLabel.isHidden = !starredCustomers.isEmpty
    emptyStarredDescLabel.isHidden = !starredCustomers.isEmpty
    followedCollectionView.isHidden = starredCustomers.isEmpty
    followedCollectionView.reloadData()
  }

  private func updatePotentialCustomersView() {
    emptyPotentialLabel.isHidden = !potentialCustomers.isEmpty
    potentialCollectionView.isHidden = potentialCustomers.isEmpty
    potentialCollectionView.reloadData()
  }

  // 关注动作
  private func followAction(user: Customer) {

    MobClick.event("follow", label: "iOS")

    let body =
      [
        "taskId": taskId,
        "unionId": user.unionId ?? "",
        "wxMemberId": user.wxMemberId ?? "",
        "headImageUrl": user.headImageUrl ?? "",
        "nickName": user.nickName,
      ] as [String: Any]

    HttpClient.shared
      .postWithAutoHUD(endpoint: "/followVisitor", body: body) {
        [weak self]
        (
          message: String?
        ) in
        guard let self = self else { return }
        if message != nil {
          DispatchQueue.main.async {
            ProgressHUD.succeed(message ?? "关注成功！")
            // 更新列表
            self.fetchCustomers()
          }
        }

      }
  }

  // 取消关注动作
  private func unfollowAction(user: Customer) {
    let body =
      [
        "taskId": taskId,
        "unionId": user.unionId ?? "",
        "wxMemberId": user.wxMemberId ?? "",
      ] as [String: Any]

    HttpClient.shared
      .postWithAutoHUD(endpoint: "/unfollowVisitor", body: body) {
        [weak self]
        (
          message: String?
        ) in
        guard let self = self else { return }

        DispatchQueue.main.async {
          ProgressHUD.succeed(message ?? "取消关注成功！")
          // 更新列表
          self.fetchCustomers()
        }

      }
  }
}

// MARK: - UISearchBarDelegate
extension CustomerViewController: UISearchBarDelegate {
  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if let textField = searchBar.value(forKey: "searchField") as? UITextField,
      textField.markedTextRange != nil
    {
      return
    }
    debounceWorkItem?.cancel()

    let workItem = DispatchWorkItem { [weak self] in
      guard let self = self else { return }
      fetchPotentialData()
    }

    debounceWorkItem = workItem
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: workItem)
  }

  func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
  }
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension CustomerViewController: UICollectionViewDataSource, UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)
    -> Int
  {
    if collectionView == followedCollectionView {
      return starredCustomers.count
    } else {
      return potentialCustomers.count
    }
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
    -> UICollectionViewCell
  {
    // 已关注
    if collectionView == followedCollectionView {
      let cell =
        collectionView.dequeueReusableCell(
          withReuseIdentifier: "FollowedCell",
          for: indexPath
        ) as! CustomerCell
      let customer = starredCustomers[indexPath.item]
      cell.configure(with: customer, which: .starred)
      cell.onStatusButtonTapped = { [weak self] in
        guard let self = self else { return }
        Alertift.alert(title: "提醒", message: "确定要取消关注吗?")
          .action(.cancel("取消"))
          .action(.destructive("确定")) {
            self.unfollowAction(user: customer)
          }
          .show()

      }
      return cell
    }
    // 高意向
    else {
      let cell =
        collectionView.dequeueReusableCell(
          withReuseIdentifier: "PotentialCell",
          for: indexPath
        ) as! CustomerCell
      let customer = potentialCustomers[indexPath.item]
      cell.configure(with: customer, which: .potential)
      cell.onStatusButtonTapped = { [weak self] in
        guard let self = self else { return }
        // 未关注
        if customer.followVisitorStatus == 0 && customer.followType == 0 {
          ProgressHUD.banner("该用户已被关注", nil)
        } else {
          self.followAction(user: customer)
        }
      }
      return cell
    }
  }

}

// MARK: - UICollectionViewDelegateFlowLayout
extension CustomerViewController: UICollectionViewDelegateFlowLayout {
  func collectionView(
    _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
  ) -> CGSize {
    // 计算每个 item 的宽度：(总宽度 - 间距 * 4) / 5
    let totalWidth = collectionView.bounds.width
    let spacing: CGFloat = 10  // 项目间距
    let itemWidth = (totalWidth - spacing * 4) / 5

    return CGSize(width: itemWidth, height: 100)
  }

  func collectionView(
    _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
    minimumInteritemSpacingForSectionAt section: Int
  ) -> CGFloat {
    return 10
  }

  func collectionView(
    _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
    minimumLineSpacingForSectionAt section: Int
  ) -> CGFloat {
    return 10
  }
}
